package com.africanmoviesmobile.ui;

import java.io.IOException;
import java.util.Vector;

import org.pixmob.httpclient.HttpClientException;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.africanmoviesmobile.R;
import com.africanmoviesmobile.util.bitmap.ImageCache.ImageCacheParams;
import com.africanmoviesmobile.util.bitmap.ImageFetcher;
import com.africanmoviesmobile.webservice.AmmWebService;
import com.africanmoviesmobile.webservice.BasicAsyncCallback;
import com.africanmoviesmobile.webservice.WebServiceException;
import com.africanmoviesmobile.webservice.inf.Celeb;
import com.africanmoviesmobile.webservice.inf.Filmography;
import com.africanmoviesmobile.webservice.inf.WebserviceObject;

public class CelebFilmographyListActivity extends BaseActivity implements OnItemClickListener, OnScrollListener {
	
	public static final String EXTRA_CELEB_ID = "celeb_id";
	public static final String EXTRA_CELEB_NAME = "celeb_name";
	
	private ListView mCelebFilmographyListView;
	
	private ImageFetcher mImageFetcher;
	
	AmmWebService mAmmWebService;
	
	private CelebFilmographyListAdapter mCelebFilmographyListAdapter;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.celeb_filmography_list_activity);
		
		final int celebId = getIntent().getIntExtra(EXTRA_CELEB_ID, 0);
		final String celebName = getIntent().getStringExtra(EXTRA_CELEB_NAME);
		
		int thumbnailWidth = getResources().getDimensionPixelSize(R.dimen.thumbnail_width);
		int thumbnailHeight = getResources().getDimensionPixelSize(R.dimen.thumbnail_height);
		mImageFetcher = new ImageFetcher(this, thumbnailWidth, thumbnailHeight);
		mImageFetcher.setLoadingImage(R.drawable.empty_photo);
		mImageFetcher.addImageCache(getSupportFragmentManager(), new ImageCacheParams(this, CACHE_DIR_THUMBNAIL));
		
		mCelebFilmographyListAdapter = new CelebFilmographyListAdapter();
		
		mCelebFilmographyListView = (ListView) findViewById(R.id.list);
		mCelebFilmographyListView.setDividerHeight(0);
		mCelebFilmographyListView.setEmptyView(findViewById(R.id.loading_progress));
		mCelebFilmographyListView.setAdapter(mCelebFilmographyListAdapter);
		mCelebFilmographyListView.setOnItemClickListener(this);
		mCelebFilmographyListView.setOnScrollListener(this);
		
		TextView celebFilmographyListHeader = (TextView) findViewById(R.id.celeb_filmography_list_header);
		celebFilmographyListHeader.setText(String.format(getResources().getString(R.string.celeb_filmography_list_header), celebName));
		
		mAmmWebService = AmmWebService.getInstance(this);
		
		mAmmWebService.getCeleb(celebId, new BasicAsyncCallback() {

			public void onComplete(final WebserviceObject[] result, final Object state) {

				Celeb celebInfo = (Celeb) result[0];		

				if ((celebInfo != null)) {
					
					Filmography[] celebFilmographies = null;
					
					try {
						celebFilmographies = (Filmography[]) celebInfo.getFilmographies();
					} catch (HttpClientException e) {
						e.printStackTrace();
					} catch (IOException e) {
						e.printStackTrace();
					} catch (WebServiceException e) {
						e.printStackTrace();
					}
					
					if ((celebFilmographies != null) && (celebFilmographies.length > 0)) {
						for (int i = 0; i < celebFilmographies.length; i++) {
							final Filmography filmography = (Filmography) celebFilmographies[i];
							runOnUiThread(new Runnable() {public void run() { mCelebFilmographyListAdapter.add(filmography); }});
						}
					}
				}
			}

			public void onHttpClientException(final HttpClientException e, final Object state) {
				Log.w("AMM HttpClientException:", e.getMessage());
			}
			
			public void onIOException(final IOException e, final Object state) {
				Log.w("AMM IOException:", e.getMessage());
			}

			public void onWebServiceException(final WebServiceException e, final Object state) {
				Log.w("AMM WebServiceException:", e.getMessage());
			}

		}, null);
		
	}
	
	@Override
    public void onResume() {
        super.onResume();
        mImageFetcher.setExitTasksEarly(false);
        mCelebFilmographyListAdapter.notifyDataSetChanged();
    }

    @Override
    public void onPause() {
        super.onPause();
        mImageFetcher.setPauseWork(false);
        mImageFetcher.setExitTasksEarly(true);
        mImageFetcher.flushCache();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mImageFetcher.closeCache();
    }
	
    @Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    	final Intent intent = new Intent(CelebFilmographyListActivity.this, MovieDetailActivity.class);
		intent.putExtra(MovieDetailActivity.EXTRA_MOVIE_ID, (int) id);
        startActivity(intent);
	}
    
    @Override
	public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		// Pause fetcher to ensure smoother scrolling when flinging
        if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_FLING) {
            mImageFetcher.setPauseWork(true);
        } else {
            mImageFetcher.setPauseWork(false);
        }
	}
    
	public class CelebFilmographyListAdapter extends BaseAdapter {

		private Vector<Filmography> mListElements = new Vector<Filmography>();
		
		private class ViewHolder {
			public TextView mMovieTitle;
			public TextView mMovieRoles;
    	    public ImageView mMovieCover;
    	}
		
        public CelebFilmographyListAdapter() {
        }

        public int getCount() {
        	if (mListElements.isEmpty()) {
    			return 0;
    		} else {
    			return mListElements.size();
    		}
        }

        public Object getItem(int position) {
        	Filmography filmography = (Filmography) mListElements.elementAt(position);
        	return filmography;
        }

        public long getItemId(int position) {
        	Filmography filmography = (Filmography) mListElements.elementAt(position);
    		return filmography.getMovieId();
        }

        public View getView(int position, View convertView, ViewGroup parent) {

        	Filmography filmography = (Filmography) mListElements.elementAt(position);

        	ViewHolder holder;
        	
        	View celebFilmographyRow = convertView;
        	
        	if(celebFilmographyRow == null){
        		LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        		celebFilmographyRow = layoutInflater.inflate(R.layout.celeb_filmography_listview_row, parent, false);
            	
            	holder  = new ViewHolder();
        		holder.mMovieTitle = (TextView) celebFilmographyRow.findViewById(R.id.movie_title);
        		holder.mMovieRoles = (TextView) celebFilmographyRow.findViewById(R.id.movie_roles);
        		holder.mMovieCover = (ImageView) celebFilmographyRow.findViewById(R.id.movie_cover);
        		
        		celebFilmographyRow.setTag(holder);
        	}else{
        		holder = (ViewHolder) celebFilmographyRow.getTag();
        	}
        	
        	holder.mMovieTitle.setText(filmography.getMovieTitle());
        	holder.mMovieRoles.setText(filmography.getRoles());
        	mImageFetcher.loadImage(filmography.getMovieCover(), holder.mMovieCover);
        	
        	return celebFilmographyRow;
        }
        
        public void add(Filmography data) {
        	mListElements.addElement(data);
            notifyDataSetChanged();
        }

    }

}
